#include "sdkconfig.h"

#include <stdio.h>
#include <cmath>
#include <vector>
#include <atomic>
#include <functional>
#include <algorithm>

#include <nvs.h>
#include <nvs_flash.h>

#include <esp_log.h>
#include <esp_err.h>
#include <esp_timer.h>
#include <esp_heap_caps.h>
#include <esp_event.h>
#include <esp_system.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "freertos/semphr.h"

#include "esp_task_manager.h"
#include "background_task.h"
#include "app.h"

#define TAG "MAIN"

const int NUM_FRAMES = 1000;  // 1000帧音频数据
const int FRAME_SIZE = 1024;  // 每帧1024个数据点

// 简单的音频编码任务
void simple_audio_encoding_task(int frame_id) {
    volatile int32_t result = 0;
    for (int i = 0; i < FRAME_SIZE; ++i) {
        for (int j = 0; j < 100; ++j) {
            result += (frame_id * i + j) % 12345;
        }
    }
    // 防止编译器优化
    if (result == 0) {
        ESP_LOGI(TAG, "计算结果为0");
    }
}

// 通用测试函数
void run_test(const char* test_name, std::function<void(std::function<void()>)> schedule_task, std::function<void()> wait_for_completion) {
    ESP_LOGI(TAG, "正在测试 %s...", test_name);
    
    std::atomic<int> completed(0);
    SemaphoreHandle_t sem = xSemaphoreCreateCounting(NUM_FRAMES, 0);
    if (sem == NULL) {
        ESP_LOGE(TAG, "创建信号量失败");
        return;
    }
    
    int64_t start_time = esp_timer_get_time();
    
    // 调度音频编码任务
    for (int i = 0; i < NUM_FRAMES; ++i) {
        schedule_task([i, &completed, sem]() {
            simple_audio_encoding_task(i);
            completed.fetch_add(1);
            vTaskDelay(pdMS_TO_TICKS(10));  // 模拟一些处理延迟
            xSemaphoreGive(sem);
        });
    }
    
    // 等待所有任务完成
    for (int i = 0; i < NUM_FRAMES; ++i) {
        xSemaphoreTake(sem, portMAX_DELAY);
    }
    
    int64_t end_time = esp_timer_get_time();
    int64_t total_time = end_time - start_time;
    
    double fps = (double)NUM_FRAMES * 1000000.0 / total_time;
    ESP_LOGI(TAG, "%s 完成，总时间: %lld 微秒 (%.2f 毫秒)", test_name, total_time, total_time / 1000.0);
    ESP_LOGI(TAG, "吞吐量: %.2f 帧/秒", fps);
    
    vSemaphoreDelete(sem);
}

// 任务管理器测试
void taskmanagerTest() {
    TaskManager& task_manager = TaskManager::GetInstance();
    auto executor = task_manager.CreateExecutor("TaskManager", 8192, 6, 1);
    if (!executor) {
        ESP_LOGE(TAG, "创建任务执行器失败");
        return;
    }
    
    run_test("任务管理器", 
        [&executor](std::function<void()> task) {
            executor->AddTask(task, TaskType::IMMEDIATE, TaskPriority::TASKHIGH, "audio_encode");
        },
        []() {
            // 任务管理器内部处理任务完成
        }
    );
}

// 后台任务测试
void backgroundTest() {
    auto background_task = new BackgroundTask(8192, "background");
    
    run_test("后台任务", 
        [background_task](std::function<void()> task) {
            background_task->Schedule(task);
        },
        []() {
            // 后台任务内部处理任务完成
        }
    );
    
    delete background_task;
}

extern "C" void app_main(void)
{
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // 运行优化后的音频编码性能测试
    taskmanagerTest();
    vTaskDelay(pdMS_TO_TICKS(1000));  // 等待1秒确保完成
    backgroundTest();
    ESP_LOGI(TAG, "所有测试已完成");
}    

